articles

Home / DeveloperSection / Articles / WindowsFormsHost control in WPF

WindowsFormsHost control in WPF

Anonymous User32704 12-Apr-2011

In XAML we can use <WindowsFormHost /> element to use WindowsFormsHost control in WPF. We know that WPF provide a great user interface, but still a very younger framework and sometime it doesn’t provide everything what we want. For example there is number of controls in Windows Forms that doesn’t exist in WPF such as DataGridView control or BindingNavigator control. So for using these controls on WPF platform we need WindowsFormsHost control. In this demonstration I will show you how to use DataGridView control in WindowsFormsHost control.

Steps to implementing WindowsFormsHost control in WPF

<![if !supportLists]> -  <![endif]> Add references of System.Windows.Forms and WindowsFormIntegration by using add Reference dialog box.

<![if !supportLists]>  <![endif]> Add following schema in XAML file

xmlns:WinForms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
 A XAML code which represents use WindowsFormsHost control in WPF
<Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition Height="40" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <WindowsFormsHost Grid.Row="0" Grid.Column="0">
            <WinForms:DataGridView x:Name="dataGridView1">   
            </WinForms:DataGridView>
        </WindowsFormsHost>
        <Button x:Name="button1" Content="Get Data" Grid.Row="1" Grid.Column="0" Click="button1_Click" />
</Grid>

 

Code for retrieving data in Data Grid View control
private void button1_Click(object sender, RoutedEventArgs e)
{
            SqlConnection con = new SqlConnection();
            con.ConnectionString = "Data Source=UTTAM-PC3\\MindStick;User Id=sa;Password=mindstick;Initial Catalog=Workbook";
            con.Open();
            string query = "select * from Student";
            SqlCommand cmd = new SqlCommand(query, con);
            SqlDataReader dr = cmd.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Load(dr);
            dataGridView1.DataSource = dt.DefaultView;
            con.Close();
}

 

Output of the following code snippet is as follows

WindowsFormsHost control in WPF

WindowsFormsHost control in WPF

 


Updated 09-Jul-2020
I am a content writter !

Leave Comment

Comments

Liked By